package jh.com.jhappbf.unload;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.view.titlebar.AbTitleBar;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.database.SQLiteDataBaseUtil;
import jh.com.jhappbf.utils.PixAndDpUtil;

/**
 * @author Administrator
 */
public class GetAddress extends AbActivity implements OnClickListener,
        OnMenuItemClickListener, OnItemClickListener {

    private EditText mEditAddress;
    private Button mAddBtn;
    private SwipeMenuListView mListView;
    private List<String> mData;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.address_get);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText(R.string.query_weight_detail_title);
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        initView();
    }

    /**
     * 刷新
     */
    private void initView() {
        mEditAddress = findViewById(R.id.address_input_edit);
        mAddBtn = findViewById(R.id.address_input_btn);
        mAddBtn.setOnClickListener(this);
        mListView = findViewById(R.id.address_list);
        SwipeMenuCreator creator = menu -> {
            SwipeMenuItem item = new SwipeMenuItem(GetAddress.this);
            item.setTitle(R.string.Address_select);
            item.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
            item.setWidth(PixAndDpUtil.dp2px(80, GetAddress.this));
            item.setTitleSize(18);
            item.setTitleColor(Color.WHITE);
            menu.addMenuItem(item);

            SwipeMenuItem deleteItem = new SwipeMenuItem(GetAddress.this);
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
            deleteItem.setWidth(PixAndDpUtil.dp2px(80, GetAddress.this));
            deleteItem.setTitleSize(18);
            deleteItem.setIcon(R.mipmap.history_item_delete);
            deleteItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(deleteItem);
        };
        mListView.setMenuCreator(creator);
        mListView.setOnItemClickListener(this);
        mListView.setOnMenuItemClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mData = new ArrayList<>();
        getData();
        mAdapter = new ArrayAdapter<>(GetAddress.this,
                android.R.layout.simple_list_item_1, mData);
        mListView.setAdapter(mAdapter);
        mListView.requestFocus();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.address_input_btn:
                addValue();
                break;
            default:
                break;
        }
    }

    /**
     * 添加地址
     */
    private void addValue() {
        String address = mEditAddress.getText().toString();
        if (address.length() == 0) {
            Toast.makeText(GetAddress.this, getResources().getString(
                            R.string.Address_input_warning_empty), Toast.LENGTH_SHORT).show();
            return;
        }

        if (isExist(address)) {
            Toast.makeText(GetAddress.this, getResources().getString(
                            R.string.Address_input_warning_repeat), Toast.LENGTH_SHORT).show();
            return;
        }

        SQLiteDatabase db = SQLiteDataBaseUtil.getDatabase(GetAddress.this);
        ContentValues values = new ContentValues();
        values.put("address", address);
        long count = db.insert("addressManager", null, values);
        if (count != -1) {
            getData();
            mAdapter.notifyDataSetChanged();
            mEditAddress.setText("");
        } else {
            Toast.makeText(GetAddress.this, getResources().getString(
                            R.string.Address_input_warning_repeat), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 删除
     */
    private void deleteItem(String address) {
        SQLiteDatabase db = SQLiteDataBaseUtil.getDatabase(GetAddress.this);
        int i = db.delete("addressManager", "address=?", new String[]{address});
        if (i > 0) {
            getData();
            mAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(GetAddress.this, getResources().getString(R.string.Address_delete_error), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 选择指定项
     */
    private void selectItem(String address) {
        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);
        Editor editor = preferences.edit();
        editor.putString("address", address);
        editor.apply();
        Intent i = new Intent();
        Bundle b = new Bundle();
        b.putString("result", address);
        i.putExtras(b);
        setResult(4, i);
        finish();
    }

    /**
     * 判断数据是否已经存在
     */
    private Boolean isExist(String name) {
        SQLiteDatabase db = SQLiteDataBaseUtil.getDatabase(getApplicationContext());
        Cursor cursor = db.query("addressManager", new String[]{"address"},
                "address=?", new String[]{name}, null, null, null, null);
        boolean result=cursor.moveToNext();
        cursor.close();
        return result;
    }

    /**
     * 读取Address
     */
    private void getData() {
        mData.clear();
        SQLiteDatabase db = SQLiteDataBaseUtil.getDatabase(getApplicationContext());
        Cursor cursor = db.query("addressManager", new String[]{"address"},
                null, null, null, null, "   id desc ");
        while (cursor.moveToNext()) {
            mData.add(cursor.getString(0));
        }
        cursor.close();
    }

    @Override
    public void onMenuItemClick(int position, SwipeMenu arg1, int index) {
        String address = mData.get(position);
        switch (index) {
            case 0:
                selectItem(address);
                break;
            case 1:
                deleteItem(address);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        String address = mData.get(position);
        selectItem(address);
    }
}
